import 'dart:io';

import 'package:dio/adapter.dart';
import 'package:dio/dio.dart';
import 'package:flutter_bilibili/core/service/utils/url_map.dart';

String ua =
    "Mozilla/5.0 (Linux; Android 5.1.1; Android SDK built for x86 Build/LMY48X) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/39.0.0.0 Mobile Safari/537.36";

class HttpBaseRequest {
  ///请求json数据
  static Map<String, dynamic> jsonHeaders = {
    HttpHeaders.acceptHeader: 'application/json,*/*',
    HttpHeaders.contentTypeHeader: 'application/json',
    HttpHeaders.userAgentHeader: ua
  };

  ///请求xml数据
  static Map<String, dynamic> xmlHeaders = {
    HttpHeaders.acceptHeader: 'application/xml,*/*',
    HttpHeaders.contentTypeHeader: 'application/xml;charset=UTF-8',
    HttpHeaders.userAgentHeader: ua
  };

  ///请求proto数据
  static Map<String, dynamic> protoHeaders = {
    HttpHeaders.acceptHeader: '*/*',
    HttpHeaders.contentTypeHeader: 'application/x-protobuf',
    HttpHeaders.userAgentHeader: ua
  };

  ///baseUrl为基本url，url为参数部分（get请求），和在一起用
  static Future<T> request<T>(String baseUrl, String url,
      {method, params, inter, contentType, responseType}) async {
    method = method ?? 'GET'; //默认情况下为GET请求
    contentType = contentType ?? 'JSON'; //请求json格式数据
    responseType = responseType ?? ResponseType.json; //响应json数据

    BaseOptions baseOption = BaseOptions(
      method: method,
      baseUrl: UrlMap.urlMap[baseUrl] as String,
      connectTimeout: 10000,
      responseType: responseType,
    );

    Dio dio = Dio(baseOption);

    //userAgent
    (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
        (HttpClient client) {
      client.userAgent = null;
    };

    ///请求头
    Map<String, dynamic> httpHeaders;
    if (contentType == 'XML') {
      httpHeaders = xmlHeaders;
    } else if (contentType == 'PROTO') {
      ///弹幕
      httpHeaders = protoHeaders;
    } else {
      httpHeaders = jsonHeaders;
    }

    ///全局拦截器
    ///创建默认的拦截器
    Interceptor dInter = InterceptorsWrapper(onRequest: (options, handler) {
      print("请求拦截");
      return handler.next(options);
    }, onError: (error, handle) {
      print("错误拦截");
      return handle.next(error);
    }, onResponse: (response, handler) {
      print("响应拦截");
      handler.next(response);
    });
    List<Interceptor> inters = [dInter];
    //请求单独拦截器
    if (inter != null) {
      inters.add(inter);
    }
    //统一添加
    dio.interceptors.addAll(inters);

    ///发送网络请求
    try {
      dio.options.headers = httpHeaders;
      Response response = await dio.request(url, queryParameters: params);

      ///返回数据
      return response.data;
    } on DioError catch (e) {
      ///返回错误
      return Future.error(e);
    }
  }
}
